<template>
  <el-row class="flex">
    <div v-if="!single">
      <div class="w-full flex flex-wrap">
        <div
          v-for="(item, index) in fileList"
          :key="index"
          class="img-list mr-5"
          @mouseover="mouseover(item, index)"
          @mousemove="mouseout(item, index)"
        >
          <div>
            <img
              class="upload-img"
              :src="item"
              :style="{ width: imgWidth, height: imgHeight }"
            />
            <span class="el-upload-list__item-actions">
              <span
                class="action-close cursor-pointer"
                :class="{ active: index == hoverIndex }"
                @click="handleRemove(item, index)"
              >
                ×
              </span>
            </span>
          </div>
        </div>
      </div>
    </div>

    <el-upload
      action="#"
      :http-request="uploadFile"
      :before-upload="checkFile"
      :on-error="uploadError"
      :show-file-list="false"
      :on-remove="handleRemove"
      :headers="uploadHeaders"
      :multiple="isMultiple"
      class="upload-btn"
    >
      <div v-if="single" class="">
        <img
          v-if="imgUrldata"
          class="upload-img"
          :src="imgUrldata"
          :style="{ width: imgWidth, height: imgHeight }"
        />
      </div>
      <img
        v-if="!imgUrldata"
        class="upload-img"
        :style="{ width: imgWidth, height: imgHeight }"
        src="@/assets/img/img_add.png"
      />
    </el-upload>
    <el-dialog v-model="dialogVisible">
      <img style="width: 100%" :src="imgUrldata" alt="Preview Image" />
    </el-dialog>
  </el-row>
  <div class="imgpreview" @click="dialogVisible = !dialogVisible" v-show="imgUrldata">
    预览
  </div>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { isVideoMime, isImageMime } from "@/utils/image";
import { getosssts } from "@/api/upload";
import OSS from "ali-oss";
const client = ref(null);
const props = defineProps({
  imgUrls: {
    type: Array, // 是否是等比例的
    default: () => [],
  },
  imgUrl: {
    type: String, // 是否是等比例的
    default: "",
  },
  isSameSize: {
    type: Boolean, // 是否是等比例的
    default: false,
  },
  lt150kb: {
    type: Boolean, // 是否是150kb
    default: false,
  },
  isMultiple: {
    // 是否可以ctrl多选
    type: Boolean,
    default: false,
  },
  imgType: {
    type: [String, Number], // 图片类型：首图，轮播图，详情图
    default: "",
  },
  imgWidth: {
    type: String, // 图片宽
    default: "",
  },
  imgHeight: {
    type: String, // 图片宽
    default: "",
  },
  single: {
    type: Boolean, // 是否只用上传一张图片
    default: false,
  },
  is500: {
    type: Boolean, // 是否图片是500*500
    default: false,
  },
});

const emit = defineEmits(["on-success", "on-remove"]);

const path = ref("");
if (import.meta.env.DEV) {
  path.value = import.meta.env.VITE_BASE_API;
}

if (import.meta.env.PROD) {
  path.value = "https://api.dropsure.com";
}

const token = localStorage.getItem("token");
const uploadHeaders = ref({});
if (token) {
  uploadHeaders.value.token = token;
} else {
  router.push({ name: "Login" });
}

// 获取密钥信息
const getosssa = () => {
  // 从后端获取密钥
  getosssts().then((res) => {
    if (res.code == 0) {
      let miyao = res.data;
      client.value = new OSS({
        // yourRegion填写Bucket所在地域。以华东1（杭州）为例，yourRegion填写为oss-cn-hangzhou。
        region: miyao.Region,
        // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
        accessKeyId: miyao.AccessKeyId,
        accessKeySecret: miyao.AccessKeySecret,
        // 从STS服务获取的安全令牌（SecurityToken）。
        stsToken: miyao.SecurityToken,
        // 填写Bucket名称。
        bucket: miyao.Bucket,
      });
    }
  });
};
// 上传文件
const uploadFile = async (file) => {
  if (file) {
    getosssts().then((res) => {
      if (res.code == 0) {
        let miyao = res.data;
        client.value = new OSS({
          // yourRegion填写Bucket所在地域。以华东1（杭州）为例，yourRegion填写为oss-cn-hangzhou。
          region: miyao.Region,
          // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
          accessKeyId: miyao.AccessKeyId,
          accessKeySecret: miyao.AccessKeySecret,
          // 从STS服务获取的安全令牌（SecurityToken）。
          stsToken: miyao.SecurityToken,
          // 填写Bucket名称。
          bucket: miyao.Bucket,
        });
        const options = {
          meta: { temp: "demo" },
          mime: "json",
          headers: { "Content-Type": "text/plain" },
        };
        try {
          let name = file.file.name;
          var pos = name.indexOf(".");
          let type = name.substr(pos);
          let now = new Date();
          const year = now.getFullYear();
          const month = (now.getMonth() + 1).toString().padStart(2, '0');
          const day = now.getDate().toString().padStart(2, '0');
          const dir = year+month+day;
          // getFileNameUUID() 生成唯一值  file.file获取文件流
          const result = client.value
            .put(`${dir}/${getFileNameUUID()}${type}`, file.file, options)
            .then((res) => {
              // 2.文件路径赋值
              console.log(res);
             uploadSuccess(res.url)

            })
            .catch((err) => {
              console.error("上传失败", err);
            });
        } catch (e) {}
      }
    });
  } else {
    ElMessage.warning({
      message: "No file selected",
      type: "warning",
    });
  }
};
// 唯一uuid
const getFileNameUUID = () => {
  function rx() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  return `${+new Date()}${rx()}${rx()}`;
};
const checkFile = async (file) => {
  // getosssa();
  // @todo 应支持在项目中设置
  const isLt3M = file.size / 1024 / 1024 < 3; // 5MB
  const isLt150KB = file.size / 1024 < 150; // 500kb
  const isVideo = isVideoMime(file.type);
  const isImage = isImageMime(file.type);
  let pass = true;
  if (!isVideo && !isImage) {
    ElMessage.error(
      "上传图片只能是 jpg,png,svg,webp 格式, 上传视频只能是 mp4,webm 格式!"
    );
    pass = false;
  }
  if (!isLt3M && isVideo) {
    ElMessage.error("上传视频大小不能超过 3MB");
    pass = false;
  }
  if (props.lt150kb && !isLt150KB) {
    ElMessage.error("上传图片不能超过150KB");
    pass = false;
  }

  if (props.isSameSize) {
    const res = await imgchecked(file);
    if (res) {
      pass = true;
    } else {
      pass = false;
    }
  }

  if (props.is500) {
    const res = await img500(file);
    if (res) {
      pass = true;
    } else {
      pass = false;
    }
  }

  return pass;
};

// 判断图片尺寸方法
const imgchecked = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file); // 必须用file.raw
    reader.onload = () => {
      // 让页面中的img标签的src指向读取的路径
      const img = new Image();
      img.src = reader.result;

      img.onload = () => {
        // if (img.width / img.height !== 2) {
        if (img.width / img.height !== 1) {
          ElMessage.error("上传得图片必须是等比例的");
          resolve(false);
        } else {
          resolve(true);
        }
      };
    };
  });
};

// 判断图片是否是500*500
const img500 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file); // 必须用file.raw
    reader.onload = () => {
      // 让页面中的img标签的src指向读取的路径
      const img = new Image();
      img.src = reader.result;

      img.onload = () => {
        // if (img.width / img.height !== 2) {
        if (img.width !== 500 || img.height !== 500) {
          ElMessage.error("上传的图片尺寸必须是500*500尺寸！");
          resolve(false);
        } else {
          resolve(true);
        }
      };
    };
  });
};

const fileList = ref([]);
let index = 0;
watch(
  () => props.imgUrls,
  (newValue, oldValue) => {
    // console.log(newValue, oldValue, 'oldValue')
    fileList.value = newValue;
    // console.log(newValue, oldValue, 'oldValue')
    index += 1;
    console.log(index, "index");
  },
  { immediate: true }
);

const imgUrldata = computed(() => {
  return props.imgUrl;
});
console.log(imgUrldata.value, "imgUrldata");

const uploadSuccess = (res) => {
  console.log(res);
  const data = res
  if (data && !props.single) {
    fileList.value.push(data)

    emit('on-success', fileList, props.imgType)
  } else if (data && props.single) {
    imgUrldata.value = data
    emit('on-success', data, props.imgType)
  }
};

const dialogVisible = ref(false);

const uploadError = () => {
  ElMessage.error("上传出错");
};

const handleRemove = (item, index) => {
  fileList.value.splice(index, 1);
  emit("on-remove", index, props.imgType);
};

const hoverIndex = ref(-1);
const mouseover = (item, index) => {
  hoverIndex.value = index;
};

const mouseout = (item, index) => {
  // hoverIndex.value = -1
};
</script>

<style lang="scss">
.upload-img {
  width: 80px;
  /* margin-right: 20px; */
}

.img-list {
  position: relative;
}

.action-close {
  position: absolute;
  right: -12px;
  top: -10px;
  display: none;
  width: 20px;
  height: 20px;
  text-align: center;
  line-height: 20px;
  border-radius: 50%;
  font-size: 18px;
  font-weight: 700;
  color: #333;
  background-color: rgba(0, 0, 0, 0.1);
  transition: all 1s linear;
  z-index: 10000;

  &.active {
    display: block;
    transition: all 1s linear;
  }
}
.imgpreview {
  width: 75px;
  text-align: center;
  color: #409eff;
  cursor: pointer;
}
/* .close-circle {
  background-color: rgba(0, 0, 0, 0.1);
} */
</style>
